package com.wanghe.stack;

import java.util.ArrayList;
import java.util.List;

/**
 * 算法20. 有效的括号
 * https://leetcode-cn.com/problems/valid-parentheses/
 */
public class Problem20 {

    private static List<Character> stack = new ArrayList<>();

    public static void main(String[] args) {
        String s = "([)]";
        System.out.println(isValid(s));
    }

    private static boolean isValid(String s) {
        if (null == s || 0 == s.length()) {
            return true;
        }
        for (int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);
            if (0 == stack.size() || '(' == c || '{' == c || '[' == c) {
                stack.add(c);
            } else {
                Character preChar = stack.remove(stack.size() - 1);
                if ((')' == c && '(' != preChar) ||
                    (']' == c && '[' != preChar) ||
                    ('}' == c && '{' != preChar)) {
                    return false;
                }
            }
        }
        if (stack.size() != 0) {
            return false;
        }
        return true;
    }

}
